import { createActions, handleActions } from 'redux-actions';
import { getRunningTaskCount } from '@api/task';
import createNoEffect from '@redux/create-no-effect';
import { get } from 'lodash';

const noEffects = createNoEffect(['SET_RUNNING_TASK_COUNT']);

const initState = {
  runningTaskCount: 0
};

export const actions = createActions({
  GET_RUNNING_TASK_COUNT: () => {
    return getRunningTaskCount()
      .then(res => {
        const runningTaskCount = get(res, 'data.data.count');
        return Promise.resolve(runningTaskCount);
      })
      .catch(err => {
        window.console.log('获取正在运行中任务出错:', err);
        return Promise.resolve(0);
      });
  },
  ...noEffects.actions
});

const reducer = handleActions(
  {
    GET_RUNNING_TASK_COUNT: (state, actions) => {
      const runningTaskCount = get(actions, 'payload') || 0;
      return {
        ...state,
        runningTaskCount
      };
    },
    ...noEffects.reducers
  },
  initState
);

export default reducer;
